<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/27
 * Time: 14:19
 */

namespace app\Flagship\Controller;


use app\Model\AccountLogModel;
use app\Model\AdminModel;
use app\Model\AdminRoleModel;
use app\Model\FlagshipModel;
use app\Model\FlagshipSetModel;
use app\Model\GoodsModel;
use app\Model\OrderGoodsModel;
use app\Model\OrderModel;
use app\Model\PluginModel;
use app\Model\RegionModel;
use app\Model\SpecGoodsPriceModel;
use think\Collection;
use think\Db;

//旗舰（分店）管理
class Flagship extends Common
{
    /*
     * 旗舰店账号页面
     */
    public function index()
    {
//        $this->_initialize();
        $postData = input('get.');
        $where = ['order_cal'=>session('Flagship.id')];
        //筛选
        $time=[0,time()];
        //筛选
        if (isset($postData['consignee'])){
            if ($postData['consignee']!=-1&&$postData['consignee']!=''){//收货人
                $where['consignee'] = ['LIKE', '%'.$postData['consignee'].'%'];
            }
            if ($postData['order_sn']){//订单编号
                $where['order_sn'] = ['=', $postData['order_sn']];
            }
            if ($postData['pay_status']!=-1&&$postData['pay_status']!=''){//支付状态
                $where['pay_status'] = ['=', $postData['pay_status']];
            }

            if ($postData['pay_code']!=-1&&$postData['pay_code']!=''){//支付方式
                $where['pay_code'] = ['=', $postData['pay_code']];
            }
            if ($postData['shipping_status']!=-1&&$postData['shipping_status']!=''){//发货状态
                $where['shipping_status'] = ['=', $postData['shipping_status']];
            }
            if ($postData['order_status']!=-1&&$postData['order_status']!=''){//订单状态
                $where['order_status'] = ['=', $postData['order_status']];
            }


            if ($postData['add_time']){//下单时间
                $postData['add_time']=explode(" - ", $postData['add_time']);//时间分割成[0]第一个 [1]第二个 取中间值
                $time[0]=strtotime($postData['add_time'][0]);
                $time[1]=strtotime($postData['add_time'][1])+86399;
            }
        }
        $getFlag =OrderModel::
            where($where)
            ->whereTime('add_time', 'between', [$time[0], $time[1]])//筛选时间
            ->order('add_time','desc')
            ->paginate(null,false,['query'=>request()->param()]);

//        dump($getFlag->toArray());die();
        $data['data'] = $getFlag;
        $order = new OrderModel();

        $data['order_status']=$order->getStatus();
//        dump($data['order_status']);die();
        $this->getConAndAct('flagship');
        return view('index',$data );
    }
    /*
      * 添加/查看进货单页面
      */
    public function add()
    {
        $getData=input('get.');
        if (isset($getData['order_id'])){
            $data['order']=OrderModel::find($getData['order_id']);   //订单信息
            if ($data['order']->order_cal!=session('Flagship.id')){
                $this->error('非法操作');
            }
            $data['goods']=OrderGoodsModel::where('order_id','=',$getData['order_id'])->select();  //已有商品
        }
        //旗舰号公共设置
       $data['fla_set']=$getRegion=FlagshipSetModel::column('val','id');
        //选择商品
        session('order_goods_set',0);
        $this->getConAndAct('order');//表明属于哪个主目录
        $data['comm']=$this->goodsEndSpec();//商品列表（包含不同规格）
        return view('add2',$data);
    }



    /*
     * 新增订单
     */
    public function addData()
    {
        $postData=input('post.');
        $this->upSess();
//        $order['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
//        $postData['shipping_name']= PluginModel::where('code','=',$postData['shipping_code'])->value('name');//物流方式name
//        $postData['pay_name'] =     PluginModel::where('code','=',$postData['pay_code'])->value('name');// 支付方式
        $money=0;//商品总价
        $money2=0;//商品内部总价
        $num_warning='';

        foreach ($postData['goods'] as $k=>$v){

            $where=['goods_id'=>$v['goods_id']];
            //判断该商品是否有规格
            $Goods= GoodsModel::where($where)->find();//商品信息
            if ($v['key']==''){//没有规格
                $moneyq=$Goods['shop_price'];//商品本店价
                $moneyq2=$Goods['cost_price'];//商品内部价
                $num= $Goods['store_count'];//商品库存
                if ($v['num']>$num){
                    $num_warning=$Goods['goods_name'].'库存不足';
                    setDatabaseDef(null,$num_warning);
                }
                //判断库存是否足够
            }else{//有规格
                $Goods2= SpecGoodsPriceModel::where($where)->where('key',$v['key'])->find();//商品信息
                $moneyq=$Goods2['price'];//规格本店价
                $num= $Goods2['store_count'];//商品库存
                $moneyq2=$Goods2['price_internal'];//商品内部价

                if ($v['num']>$num){
                    $num_warning=$Goods['goods_name'].$Goods2['key_name'].'库存不足';
                    setDatabaseDef(null,$num_warning);

                }
            }
            $moneyq = $moneyq*$v['num'];//本店价*数量
            $moneyq2 = $moneyq2*$v['num'];//内部价*数量
            $money+=$moneyq;//商品总价
            $money2+=$moneyq2;//商品内部总价
        }
        //旗舰店内部价

        $Fla_set=FlagshipSetModel::select()->column('val','id');//加盟店公共设置
        if (session('Flagship.is_one')==0){//如果是加盟店第一单
            if ($money2<$Fla_set[2]){//首单数量不足
                setDatabaseDef(null,'旗舰店首单需要消费金额：￥'.$Fla_set[2]);
            };
            FlagshipModel::where('id',session('Flagship.id'))->update(['is_one'=>1]);
        }
        if ($money2<$Fla_set[5]){//首单数量不足
            setDatabaseDef(null,'旗舰店需要消费金额：￥'.$Fla_set[5]);
        };
        if (session('Flagship.balance')<$money2){//余额不足判断
            $mon=$money2-floatval(session('Flagship.balance'));
            setDatabaseDef(null,'余额不足,超额￥'.$mon);

        }
        $postData['user_id']=session('Flagship.id');//商品总价
        $postData['goods_price']=$money;//商品总价
        $postData['shipping_price']= 0;//计算物流费用  参数：商品【】、数量【】、物流方式、
        $postData['order_amount']= $money2+$postData['shipping_price']; // 应付金额（去除积分、优惠、余额 所需支付的金额 目前不需要，金额+物流）
        $postData['total_amount']   = $money2; // 订单总价（目前只需要金额）
        //去除订单表不需要的字段

        $postData['add_time']=time();//订单添加时间
        $postData['pay_code']='yue';//支付方式
        $postData['pay_name']='余额';//支付方式--中文
        $postData['pay_status']=1;//订单支付状态--已支付
        $postData['pay_time']=time();//订单支付时间

        $postData['order_sn']=date('YmdHis').rand(1000,9999);//订单编号
        $postData['order_cal']=session('Flagship.id');
        unset($postData['goods_id']);//去除商品id
        $goods_data=$postData['goods'];
        unset($postData['goods']);//去除商品数据
        dump($postData);die();
        $setOrder = OrderModel::insertGetId($postData);//新增订单 获取id

        setDatabaseDef($setOrder,'订单表操作失败');


        if (session('Flagship.is_one'))
        if($setOrder){
            $orderArray=[];
            foreach ($goods_data as $k=>$v){
                $goods=GoodsModel::find($v['goods_id']);
                $val['order_id'] = $setOrder;//自增订单id
                $val['goods_id'] = $v['goods_id'];//商品id
                $val['goods_name']=$goods->goods_name;//商品名称
                $val['goods_sn']=$goods->goods_sn;//商品编号
                $val['goods_num']=$v['num'];//数量
                $val['market_price']=$goods['market_price'];//市场价
                $val['goods_price']=$goods->shop_price;//本店价
                $val['spec_key']='';//商品规格key
                $val['spec_key_name']='';//规格对应中文
                $val['member_goods_price']=$goods->shop_price;//会员折扣价（管理员添加无需折扣）
                if ($v['key']!=''){//有规格
                    $spec_data=SpecGoodsPriceModel::where('goods_id',$v['goods_id'])->where('key',$v['key'])->find();
                    $val['spec_key']=$spec_data->key;//商品规格key
                    $val['spec_key_name']=$spec_data->key_name;//规格对应中文
                    $val['goods_price']=$spec_data->price;//规格本店价
                    $val['cost_price']=$spec_data->price_internal;//商品规格成本价
                }else{
                    $val['cost_price']=$goods->cost_price;//商品成本价
                }
//                $val['give_integral']=$v['give_integral'];//购买商品赠送积分
//                $val['member_goods_price']=$v['member_goods_price'];//会员折扣价

//                $val['bar_code']=$v['bar_code'];//条码
//                $val['is_comment']=$v['is_comment'];//是否评价
//                $val['prom_type']=$v['prom_type'];//0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠
//                $val['prom_id']=$v['prom_id'];//活动id
//                $val['is_send']=$v['is_send'];//0未发货，1已发货，2已换货，3已退货
//                $val['delivery_id']=$v['delivery_id'];//发货单id
                array_push($orderArray,$val);
            }
            $serOrderGoods=OrderGoodsModel::insertAll($orderArray);//订单与商品链接表添加数据
            setDatabaseDef($serOrderGoods,'订单与商品链接表添加失败');
        }
        //扣除用户余额
        FlagshipModel::where('id',session('Flagship.id'))->setDec('balance',$money2);
        //资金变动记录
        $this->accountLog($money2*-1,'加盟商消费'.$money2,$setOrder,$postData['order_sn']);
        $this->upSess();
        return retJson('',200,'订单操作成功余额减少'.$money2);
    }

    /*
     * 编辑订单页面
     */
    public function edit()
    {

        $getData=input('get.');
        $data['order']=OrderModel::find($getData['order_id']);   //订单信息

        if ($data['order']->order_status!=0){$this->error('只有未确定订单可以编辑');};
        $data['province']=RegionModel::where('level','=',1)->select();//省数据
        $data['city']=RegionModel::where('level','=',2)->select();//市数据
        $data['district']=RegionModel::where('level','=',3)->select();//县、区数据

//       dump($getGoods->toArray());die();
        $data['comm']=$this->goodsEndSpec();//商品列表（包含不同规格）
        $data['goods']=OrderGoodsModel::where('order_id','=',$getData['order_id'])->select();  //已有商品
        return view('edit',$data);
    }

    /*
     * 删除
     */
    public function del(){
        $postData = input('post.');


        $delRole = FlagshipModel::destroy($postData['id']);
        return setDatabase($delRole);
    }
    /*
    * 收货
    */
    public function receive(){
        $postData = input('post.');

        $getOrder=OrderModel::find($postData['id']);
        if ($getOrder->order_cal!=1||$getOrder->user_id!=session('Flagship.id')){
            return retJson('',201,'非法操作');
        }
        if($getOrder->shipping_status==2){
            return retJson('',201,'已收货订单无需再次收货');
        }

        $updata=[   'shipping_status'=>2,// 已收货
                    'confirm_time'=>time()// 收货确认时间
        ];
        $this->setOrderC($postData['id'],$updata,'加盟商确认收货','确认收货订单完成');
        return retJson('',200,'确认收货');
//        $row = OrderModel::update($data);
//        return setDatabase($row,'收货');
    }
    
    /*
     * 充值页面
     */
    public function voucher_center()
    {
        return view();
    }
    /*
     * 充值
     */
    public function voucher()
    {
        $getData=input('post.');
        $where=['id'=>session('Flagship.id')];
        $setDatabase=FlagshipModel::where($where)->setInc('balance',$getData['balance']);
        $this->accountLog($getData['balance'],'用户充值'.$getData['balance']);
        $this->upSess();
       return setDatabase($setDatabase);
    }
    
    /*
     * 资金明细
     */
    public function capital_log()
    {
        $postData = input('get.');

        $where = [ 'user_type'=>1,                              //只显示加盟商资金
                    'user_id'=>session('Flagship.id')   //只显示加盟商个人资金
        ];
        $time=[0,time()];

        if (isset($postData['nickname'])){
            if ($postData['nickname']){
                $where['nickname'] = ['LIKE', '%'.$postData['nickname'].'%'];
            }
            if ($postData['ctime']){
                $postData['ctime']=explode(" - ", $postData['ctime']);//时间分割成[0]第一个 [1]第二个 取中间值
                $time[0]=strtotime($postData['ctime'][0]);
                $time[1]=strtotime($postData['ctime'][1])+86399;
            }
        }

        $getRecharge= AccountLogModel::
        order('change_time','desc')
            ->where($where)//筛选
            ->whereTime('change_time', 'between', [$time[0], $time[1]])//筛选时间
            ->paginate(null,false,['query'=>request()->param()]);
        $data['data'] = $getRecharge;
        return view('capital_log',$data);
    }

    /*
     * 实验区--数组移除jquery
     */
    public function sy1()
    {
//        session('aa',null);
        dump(session('aa'));
        return view();
    }
    
    /*
     * 定时执行
     */
    public function dszx()
    {
//        ignore_user_abort();//关闭浏览器后，继续执行php代码
//
//        set_time_limit(0);//程序执行时间无限制
//
        session('aa',0);
        $sleep_time = 1;//多长时间执行一次
        $a=0;

        while($a<5){
            sleep($sleep_time);
            $a+=1;
            dump(date('H:i:s',time()));
//            session('aa',$a);

        }
        exit();

//        do{
//
//            $a+=1;
//            session('aa',$a);
////            dump(session('aa'));
//            sleep($sleep_time);
//        }while(true);
    }
}